package com.vf.s.mvc.biz.controller;


import java.io.File;
import java.util.List;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.vf.core.controller.BaseController;
import com.vf.core.util.UuidUtil;
import com.vf.core.util.ZipUtil;
import com.vf.s.common.model.biz.BizModel;
import com.vf.s.common.model.biz.BizPanorama;
import com.vf.s.common.model.biz.BizPicture;
import com.vf.s.common.model.biz.BizProperty;
import com.vf.s.common.model.biz.BizText;
import com.vf.s.common.model.biz.BizVideo;
import com.vf.s.common.model.scene.BizSceneModel;

public class ModelController extends BaseController {
	
	public void index() {
		this.render("list.html");
	}
	
	public void modelForEdit() {
		this.set("sceneId", getPara("sceneId"));
		this.render("modelForEdit.html");
	}
	
	public void modelForObjEdit() {
		this.set("sceneId", getPara("sceneId"));
		this.render("modelForObjEdit.html");
	}
	
	public void selectList() {
		set("sceneId", getPara("sceneId"));
		set("targetId", getPara("targetId"));
		render("selectList.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String name = getPara("name");
		String type = getPara("type");
		String sceneId = getPara("sceneId");
		String select = " select *  ";
		String sqlExceptSelect = " from " + BizModel.TABLE_NAME + " o  where 1=1 ";
		if (!StrKit.isBlank(name)) {
			sqlExceptSelect += " and o.name like '%" + name + "%'  ";
		}
		if (!StrKit.isBlank(type)) {
			sqlExceptSelect += " and o.type = '" + type + "'  ";
		}
		
		if (!StrKit.isBlank(sceneId)) {
			select ="select o.*,(CASE WHEN (select COUNT(id) from biz_layer b WHERE b.sceneId='"+sceneId+"' and  o.id=b.dataId and b.type='"+type+"') >0 THEN true ELSE false END)  as LAY_CHECKED  ";
			//sqlExceptSelect += " order by  LAY_CHECKED desc  ";
		}
		Page<BizModel> page = BizModel.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}

	public void save() {
		BizModel role = getModel(BizModel.class);
		if (StrKit.notBlank(role.getId())) {
			BizModel namerole=BizModel.dao.findFirst("SELECT * FROM "+BizModel.TABLE_NAME +" WHERE NAME=? AND ID!=?",role.getName(),role.getId());
			if(namerole!=null) {
				renderError("名称已存在！");
				return ;
			}
			if (role.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			BizModel namerole=BizModel.dao.findFirst("SELECT * FROM "+BizModel.TABLE_NAME +" WHERE NAME=?",role.getName());
			if(namerole!=null) {
				renderError("名称已存在！");
				return ;
			}
			role.setId(UuidUtil.getUUID());
			if (role.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	/***
	 * 删除
	 * @throws Exception
	 */
	public void delete() {
		BizModel model = BizModel.dao.findById(this.getPara("id"));
		if (model != null) {
			if (model.delete()) {
				renderSuccess("删除成功！");
				
				try {
					if(!StrKit.isBlank(model.getImg())) {
						File file = new File(rootPath+model.getImg());
						if(file.exists()) {
							file.delete();
						}
					}
					if(!StrKit.isBlank(model.getUrl())) {
						File file = new File(rootPath+model.getUrl());
						if(file.exists()) {
							file.delete();
						}
					}
				}catch (Exception e) {
				}
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}

	private String rootPath = PathKit.getWebRootPath();
	public void upload() {
		UploadFile uploadFile = getFile();
		try {
			String path = "/upload/model" + "/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			
			uploadFile.getFile().renameTo(file);
			
			List<String> paths = ZipUtil.unZip(file, rootPath+path);
			
			if(paths!=null && paths.size()>0) {
				BizModel bizModel = new BizModel();
				bizModel.setId(UuidUtil.getUUID());
				bizModel.setName(paths.get(0));
				bizModel.setSource("0");
				bizModel.setEnabled("1");
				bizModel.setUrl(path.replace(".zip", "")+"/"+paths.get(0));
				if(paths.get(0).contains(".gltf")) {
					bizModel.setType("GLTF");
				}else {
					bizModel.setType("3DTILES");
				}
				if(bizModel.save()) {
					if (file.exists()) {
						file.delete();
					}
					renderSuccess("上传成功！");
				}else {
					renderError("上传失败！");
				}
			}else {
				renderError("上传失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}
	
	public void addModelToLayer() {
		String modelId=getPara("modelId");
		String status=getPara("status");
		String sceneId=getPara("sceneId");
		String layerId=getPara("layerId");
		
		BizModel bizModel=BizModel.dao.findById(modelId);
		if(bizModel!=null) {
			if(StrKit.equals("0",status)) {
				BizSceneModel bizSceneModel=BizSceneModel.dao.findFirst("select * from "+BizSceneModel.TABLE_NAME+" where modelId=? and sceneId=? and layerId=? ",modelId,sceneId,layerId);
				if(bizSceneModel!=null && bizSceneModel.delete()) {
					renderSuccess("删除成功！",bizSceneModel);
					Db.delete("DELETE FROM " + BizProperty.TABLE_NAME + " WHERE OBJID=? ", bizSceneModel.getId());
					Db.delete("DELETE FROM " + BizPicture.TABLE_NAME + " WHERE OBJID=? ", bizSceneModel.getId());
					Db.delete("DELETE FROM " + BizVideo.TABLE_NAME + " WHERE OBJID=? ", bizSceneModel.getId());
					Db.delete("DELETE FROM " + BizPanorama.TABLE_NAME + " WHERE OBJID=? ", bizSceneModel.getId());
					Db.delete("DELETE FROM " + BizText.TABLE_NAME + " WHERE OBJID=? ", bizSceneModel.getId());
				}else {
					renderError("删除失败!");
				}
			}else {
				BizSceneModel bizSceneModel=BizSceneModel.dao.findFirst("select * from "+BizSceneModel.TABLE_NAME+" where modelId=? and sceneId=? and layerId=? ",modelId,sceneId,layerId);
				if(bizSceneModel==null) {
					bizSceneModel = new BizSceneModel();;
					bizSceneModel.setId(UuidUtil.getUUID());
					bizSceneModel.setName(bizModel.getName());
					bizSceneModel.setType(bizModel.getType());
					bizSceneModel.setUrl(bizModel.getUrl());
					bizSceneModel.setSceneId(sceneId);
					bizSceneModel.setLayerId(layerId);
					bizSceneModel.setModelId(bizModel.getId());
					if(bizSceneModel.save()) {
						renderSuccess("成功！",bizSceneModel);
					}else {
						renderError("失败!");
					}
				}else {
					bizSceneModel.setName(layerId);
					bizSceneModel.setType(bizModel.getType());
					bizSceneModel.setUrl(bizModel.getUrl());
					bizSceneModel.setSceneId(sceneId);
					bizSceneModel.setLayerId(layerId);
					bizSceneModel.setModelId(bizModel.getId());
					if(bizSceneModel.update()) {
						renderSuccess("成功！",bizSceneModel);
					}else {
						renderError("失败!");
					}
				}
			}
		}else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	/**
	 * 保存模型至场景
	 */
	public void saveModelToScene() {
		BizSceneModel model = getModel(BizSceneModel.class);
		BizSceneModel dbBizSceneModel=BizSceneModel.dao.findById(model.getId());
		if(dbBizSceneModel!=null) {
			if(model.update()) {
				renderSuccess("更新成功！",model);
			}else {
				renderError("更新失败！");
			}
		}else {
			if(model.save()) {
				renderSuccess("添加成功！",model);
			}else {
				renderError("添加失败！");
			}
		}
	}
	
	public void menu() {
		this.set("sceneId", this.get("sceneId"));
		BizModel bizModel=BizModel.dao.findById(get("modelId"));
		this.set("bizModel", bizModel);
		render("modelmenu.html");
	}
	
	public void edit() {
		this.set("sceneId", this.get("sceneId"));
		this.set("id", this.get("id"));
		BizSceneModel bizSceneModel=BizSceneModel.dao.findById(this.get("id"));
		if(StrKit.equals("3DTILES", bizSceneModel.getType())) {
			this.set("bizSceneModel", bizSceneModel);
			render("editFor3DTileset.html");
		}
		else if(StrKit.equals("GLTF", bizSceneModel.getType())) {
			this.set("bizSceneModel", bizSceneModel);
			render("editForGLTF.html");
		}
	}
	
	public void uploadThumbnail() {
		UploadFile uploadFile = getFile();
		try {
			String id=this.getPara("id");

			if(StrKit.isBlank(id)) {
				renderError("参数必填！");
				return;
			}
			
			BizModel model = BizModel.dao.findById(id);
			if(model==null) {
				renderError("参数无效！");
				return;
			}
			String path = "/upload/model/"+id+"/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			model.setImg(path);
			if(uploadFile.getFile().renameTo(file)) {
				model.update();
				renderSuccess("成功！",model);
			}else {
				renderError("失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}
	
	
}
